package com.his.elasticsearch.service.Imp;

import com.his.dictitem.dao.DictItemMapper;
import com.his.dictitem.entity.DictItem;
import com.his.elasticsearch.repository.DictItemRepository;
import com.his.elasticsearch.service.DictItemService;
import org.elasticsearch.index.query.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author xiaoxiaoping
 * @Date 2020/3/12 10:38
 * @Version 1.0
 */
@Service("item-impl")
public class DictItemServiceImpl implements DictItemService {
    @Resource
    private DictItemRepository dictItemRepository;
    @Autowired
    private DictItemMapper dictItemMapper;
    @Override
    public void insertAll() {
        DictItem dictItem = new DictItem();
        List<DictItem> list = dictItemMapper.selectByEntity(dictItem);
        dictItemRepository.saveAll(list);
    }

    @Override
    public List<DictItem> queryByCateName(String CateName,String hospId,String cateId) {
        DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        QueryBuilder ikNameQuery = QueryBuilders.matchQuery("itemname", CateName);
        QueryBuilder pinyinNameQuery = QueryBuilders.matchQuery("itemname.pinyin", CateName);
        QueryBuilder hospIdQuery = QueryBuilders.termQuery("hospid",hospId);
        QueryBuilder cateIdQuery = QueryBuilders.matchQuery("cateid",cateId);
        //disMaxQueryBuilder.add(ikNameQuery);
        disMaxQueryBuilder.add(pinyinNameQuery);
        builder.must(hospIdQuery);
        builder.must(cateIdQuery);
        builder.should(ikNameQuery);
        //builder.should(ikNameQuery);
        builder.should(pinyinNameQuery);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(builder)
                .build();
        System.out.println(searchQuery.getQuery().toString());
        List<DictItem> list  = dictItemRepository.search(searchQuery).getContent();
        //List<com.his.elasticsearch.dictitem.DictItemCategory> list = elasticsearchTemplate.queryForList(queryBuilder, com.his.elasticsearch.dictitem.DictItemCategory.class);
        //Iterable<com.his.elasticsearch.dictitem.DictItemCategory> searchResult =  dictItemCategoryRepository.search(QueryBuilders.prefixQuery("catename.pinyin", CateName));
         //searchResult.forEach(e->list.add(e));
         return  list;
    }

    @Override
    public void save(DictItem dictItem) {
        dictItemRepository.save(dictItem);
    }
}
